import { defineStore } from "pinia";
import { RouteRecordRaw } from "vue-router";
import { getMenuData } from "/@/api/home/menu";
import { MenuItem } from "/@/api/home/menu/models";
import router from "/@/router";
import authCache from "/@/utils/cache/authCache";
import { firstCharToUpper } from "/@/utils/common";

//部分复杂页面路由与页面组件路径映射关系
const pageUrlPath = {
  TollBoothManagement: "TollBoothManagement/TollBoothManagement",
};
function getPageComponentPath(pageUrl: string) {
  pageUrl = firstCharToUpper(pageUrl);
  return pageUrlPath[pageUrl] || pageUrl;
}

const dynamicModules = import.meta.glob("../views/**/*.vue");

function handleMenuItem(routeData: RouteRecordRaw[], rootRouteName: string, item: MenuItem, parentItems: MenuItem[]) {
  if (item.children && item.children.length > 0) {
    parentItems.push(item);
    item.children.forEach((el) => {
      handleMenuItem(routeData, rootRouteName, el, parentItems);
    });
  } else {
    let parentActions: string[] = [rootRouteName].concat(parentItems.map((el) => el.path));
    const route: RouteRecordRaw = {
      path: `/${parentActions.join("/")}/${item.path}`,
      name: item.path,
      component: dynamicModules[`../views/${rootRouteName}/${getPageComponentPath(item.path)}.vue`],
    };
    item.path = route.path;
    //动态加入路由数据
    router.addRoute(rootRouteName, route);
    routeData.push(route);
  }
}

export function handleMenuSort(menuData?: MenuItem[]) {
  if (menuData && menuData.length > 0) {
    menuData.sort((a, b) => {
      return a.orderNum - b.orderNum;
    });
    menuData.forEach((menuItem) => {
      handleMenuSort(menuItem.children);
    });
  }
}

export const useMenuStore = defineStore("menu", {
  state: (): { menuData: MenuItem[] } => {
    return {
      menuData: [],
    };
  },
  actions: {
    /**
     * 初始化菜单和路由
     * 将菜单转化为路由数据 并加入到vueRouter中
     */
    async initAuthMenu({ rootRouteName }: { rootRouteName: string }) {
      const userInfo = authCache.getUserInfo();
      if (!userInfo) return null;
      const menuData = await getMenuData();
      if (!menuData) return null;
      handleMenuSort(menuData);
      const routeData: RouteRecordRaw[] = [];
      this.menuData = menuData;
      menuData.forEach((item) => {
        handleMenuItem(routeData, rootRouteName, item, []);
      });
      return routeData;
    },
  },
});
